package com.jaywalkable.vkeyboard;

import java.util.NavigableSet;
import java.util.TreeMap;

import com.jaywalkable.vkeyboard.impl.SimpleVTextComponent;

class VKeyboardKeyConverterImpl implements VKeyboardKeyConverter {
    private final NavigableSet<String> descendingKeySet;
    private final TreeMap<String, Character[]> keyMap;
    private boolean foundOnePrefixMatch = false;
    private boolean foundMultiplePrefixMatch = false;

    protected VKeyboardKeyConverterImpl(TreeMap<String, Character[]> keyMap) {
        super();
        this.descendingKeySet = keyMap.descendingKeySet();
        this.keyMap = keyMap;
    }

    public String applyDecodingRules(String str) {
        VTextComponent vTextComponent = new SimpleVTextComponent();
        VKeyboardImpl kb = new VKeyboardImpl(vTextComponent);
        kb.setConverter(this);
        // CharBuffer cb = CharBuffer.wrap(str);
        for (int i = 0; i < str.length() - 1; i++) {
            kb.keyPressed(str.charAt(i));
        }
        return vTextComponent.getText();
    }

    public Character[] convert(String sin) {
        foundMultiplePrefixMatch = false;
        foundOnePrefixMatch = false;
        String prefix = sin;
        Character[] converted = null;
        for (String key : this.descendingKeySet) {
            if (!foundOnePrefixMatch) {
                foundOnePrefixMatch = key.startsWith(prefix);
            } else if (!foundMultiplePrefixMatch) {
                foundMultiplePrefixMatch = key.startsWith(prefix);
            }
            if (key.equals(sin)) {
                converted = this.keyMap.get(key);
            }
        }
        
        return converted;
    }

    public boolean foundMultiplePrefixMatch() {
        return foundMultiplePrefixMatch;
    }

    public boolean foundOnePrefixMatch() {
        return foundOnePrefixMatch;
    }

    public boolean foundExactMatchOnly() {
        return foundOnePrefixMatch() && !foundMultiplePrefixMatch();
    }

    @Override
    public TreeMap<String, Character[]> getKeyMap() {        
        return keyMap;
    }
}
